<script lang="ts" setup>
import type { DataType, RowType } from './types';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { Page, useVbenModal } from '@vben/common-ui';

import {
  Button,
  message,
  Modal,
  Popconfirm,
  Space,
  Switch,
  Tag,
} from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteRoutes, getRoutes, postRoutesToggle } from '#/api/admin/routes';
import Icon from '#/components/Icons';
import { formatImagesList, sortByField, toggleStatus } from '#/utils';

import { FormModalView } from './components';

defineOptions({
  name: 'AdminRoute',
});

const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
const viewTitle = routeMeta.title.replace('管理', '');

const gridOptions: VxeGridProps<RowType> = {
  rowConfig: {
    isCurrent: true,
    isHover: true,
  },
  columns: [
    { title: '序号', type: 'seq', width: 50 },
    { field: 'full_url', title: '原始网址' },
    { field: 'url', title: '显示网址' },
    { field: 'type', title: '类型', slots: { default: 'type' } },
    { field: 'status', title: '状态', slots: { default: 'status' } },
    {
      slots: { default: 'action' },
      field: 'action',
      fixed: 'right',
      title: '操作',
      width: 240,
    },
  ],
  height: 'auto',
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async () => {
        const { data } = await getRoutes();
        const list = sortByField(data.list, 'list_order');
        data.list = formatImagesList(list);
        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
});

const handleDelete = async (row: DataType) => {
  const $table = GridApi.grid;
  if ($table) {
    const { msg } = await deleteRoutes(row.id);
    $table.remove(row);
    message.success(msg);
  }
};

const onChange = async (row: DataType) => {
  Modal.confirm({
    title: '系统提示',
    content: `确认要${row.status === 0 ? '停用' : '启用'}吗?`,
    async onOk() {
      try {
        await postRoutesToggle(row.id);
        message.success(`已${row.status === 0 ? '停用' : '启用'}`);
      } catch {
        row.status = toggleStatus(row.status);
      }
    },
    onCancel() {
      row.status = toggleStatus(row.status);
    },
  });
};

const [FormModal, formModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: FormModalView,
  onClosed() {
    const formModalData = formModalApi.getData();
    if (formModalData?.isUpdata) {
      GridApi.query();
    }
  },
});

const openDialog = async (title: '新增' | '编辑', row?: null | RowType) => {
  formModalApi.setState({
    title: `${title}${viewTitle}`,
  });
  formModalApi.setData(row);
  formModalApi.open();
};
</script>

<template>
  <Page auto-content-height>
    <FormModal />
    <Grid :table-title="`${viewTitle}列表`">
      <template #toolbar-tools>
        <Button class="mr-2" type="primary" @click="openDialog('新增')">
          <span class="anticon">
            <Icon icon="ri:add-line" />
          </span>
          新增{{ viewTitle }}
        </Button>
      </template>

      <template #type="{ row }">
        <Tag :color="row.type === 1 ? 'success' : 'default'" effect="dark">
          {{ row.type === 1 ? '自定义' : '系统' }}
        </Tag>
      </template>
      <template #status="{ row }">
        <Switch
          v-model:checked="row.status"
          :checked-value="1"
          :disabled="row.type === 2"
          :un-checked-value="0"
          checked-children="启用"
          un-checked-children="停用"
          @change="onChange(row)"
        />
      </template>

      <template #action="{ row }">
        <Space>
          <Button
            :disabled="row.type === 2"
            type="primary"
            @click="openDialog('编辑', row)"
          >
            <template #icon>
              <span class="anticon">
                <Icon icon="ri:file-edit-line" />
              </span>
            </template>
            编辑
          </Button>
          <Popconfirm
            :disabled="row.type === 2"
            cancel-text="否"
            ok-text="是"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <Button :disabled="row.type === 2" danger type="primary">
              <template #icon>
                <span class="anticon">
                  <Icon icon="ri:delete-bin-line" />
                </span>
              </template>
              删除
            </Button>
          </Popconfirm>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
